package me.itblog.mvc.modules.admin;

import com.rometools.rome.feed.synd.SyndCategory;
import me.itblog.bean.Article;
import me.itblog.bean.Category;
import me.itblog.bean.User;
import me.itblog.mvc.filter.AdminAuthcActionFilter;
import me.itblog.mvc.modules.BaseModule;
import me.itblog.services.ArticleLuceneService;
import me.itblog.services.CacheManager;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Param;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by infi.he on 2015/12/23.
 */
@IocBean()
@At("/admin/article")
@Filters(@By(type = AdminAuthcActionFilter.class))
public class AdminArticleModule extends BaseModule {

    @Inject
    ArticleLuceneService articleLuceneService;
    @Inject
    CacheManager cacheManager;

    @At("/rebuild")
    public NutMap rebuild() throws Exception {
        articleLuceneService.rebuild();
        return ajaxOk("");
    }

    @At("/save")
    //{context: "<p>fdddddddddddd</p>", title: "fdsafdsafd", author: "4ig4ofb0lmg86qef6o41iaclpd|OneAPM 博客",
    // categorys: "1v2jvapbgiivnou6qtiqdlqdec|Framework & Tool;5atl496c8iihupbi96rdi57d9h|RESTful"}
    public NutMap save(@Param("title") String title,@Param("author") String author,@Param("categorys") String categorys,
                       @Param("context") String context) throws Exception {

        Article article = new Article();
        article.setTitle(title);
        article.setContents(context);
        String[] split = author.split("\\|");
        article.setAuthorId(split[0]);
        article.setAuthorName(split[1]);
        List<Category> categories = new ArrayList<Category>();

        try {
            String[] categoryStr = categorys.split(";");
            for (String s : categoryStr) {
                String[] category = s.split("\\|");
                String categoryId = category[0];
                Category dbCategory = dao.fetch(Category.class, Cnd.where("id", "=", categoryId));
                dbCategory.setCnt(dbCategory.getCnt() + 1);
                dao.update(dbCategory, "cnt|updateTime");
                categories.add(dbCategory);
            }
        }catch (Exception e){}
        article.setCategoryList(categories);
        article.setCategorys(categorys);
        article.setPublishedDate(new Date());

        dao.insert(article);
        dao.insertRelation(article, "categoryList");
        cacheManager.cacheNewArtivle(article);
        articleLuceneService.addArticle(article);
        return ajaxOk("");
    }
}
